package com.time.company.components.task;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.MultiImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.sina.weibo.sdk.utils.Utility;
import com.time.company.R;
import com.time.company.app.AppConfig;
import com.time.company.app.WXManager;
import com.time.company.base.BaseActivity;
import com.time.company.base.BasePW;
import com.time.company.components.popup.SharePW;
import com.time.company.servermodel.Share;
import com.time.company.utils.ShareUtils;
import com.time.company.utils.ToastUtils;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.youzan.androidsdk.basic.YouzanBrowser;
import com.youzan.androidsdk.basic.web.bridge.IBridgeEnv;
import com.youzan.androidsdk.basic.web.event.ShareDataEvent;
import com.youzan.androidsdk.model.goods.GoodsShareModel;
import com.zhy.base.fileprovider.FileProvider7;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 时间商城
 * Created by Bing on 2018/2/2.
 * E-mail is tx16bing@163.com
 */

public class YouZanMarkerActivity extends BaseActivity implements WbShareCallback {

    private static final int SHARE_PW_REQUEST_CODE = 105;

    private LinearLayout mParent;
    private YouzanBrowser mWebView;

    private WindowManager.LayoutParams attributes;
    private SharePW sharePW;
    private Share curShare;
    private String localPicUrl;

    // Sina share
    public WbShareHandler shareHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_you_zan_web);
        assignViews();
        // Init sina share
        shareHandler = new WbShareHandler(this);
        shareHandler.registerApp();
    }

    private void assignViews() {
        mParent = findView(R.id.ll_parent);
        findView(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mWebView.pageGoBack()) {
                    finish();
                }
            }
        });
        findView(R.id.iv_web_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 触发分享
                mWebView.sharePage();
            }
        });
        mWebView = findView(R.id.web_view);
        // 订阅分享回调
        mWebView.subscribe(new ShareDataEvent() {
            @Override
            public void call(IBridgeEnv iBridgeEnv, GoodsShareModel data) {
                curShare = new Share();
                curShare.setAddress(data.getLink());
                curShare.setTitle(data.getTitle());
                curShare.setDescribe(data.getDesc());
                curShare.setPicUrl(data.getImgUrl());
                Logger.i("Current share " + curShare.toString());

                andPermission(SHARE_PW_REQUEST_CODE, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE});
            }
        });
        mWebView.loadUrl("https://j.youzan.com/6cRAIY");
    }

    private void andPermission(int requestCode, String[] permissions) {
        AndPermission.with(this)
                .requestCode(requestCode)
                .permission(permissions)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(YouZanMarkerActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == SHARE_PW_REQUEST_CODE) {
                AppConfig.getInstance().initDir();
                if (sharePW == null || !sharePW.isShowing()) {
                    launchShare();
                }
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            AppConfig.getInstance().initDir();
            // 即使是用户选择了不在询问还是会toast该提示语
            if (requestCode == SHARE_PW_REQUEST_CODE) {
                ToastUtils.showShort(getString(R.string.permission_external_storage));
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(YouZanMarkerActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(YouZanMarkerActivity.this, 404).show();
            }
        }
    };

    private void launchShare() {
        final Window window = getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        sharePW = new SharePW(this, mParent);
        sharePW.setOnItemClickListener(new BasePW.OnItemClickListener<Object>() {
            @Override
            public void onItemClick(final int type, Object result) {
                ShareUtils.getInstance().getSharePicPath(curShare.getPicUrl(), "share.jpg",
                        new ShareUtils.ShareCallback() {
                            @Override
                            public void onSucceed(String path) {
                                localPicUrl = path;
                                if (TextUtils.isEmpty(localPicUrl)) {
                                    localPicUrl = ShareUtils.getInstance().getSharePicPath("share.jpg");
                                }
                                if (type == resources.getInteger(R.integer.share_type_wx)) {
                                    //　分享给微信朋友
                                    shareMoment(curShare, false, localPicUrl);
                                } else if (type == resources.getInteger(R.integer.share_type_wx_publish)) {
                                    //　分享给微信朋友圈
                                    shareMoment(curShare, true, localPicUrl);
                                } else if (type == resources.getInteger(R.integer.share_type_wb)) {
                                    // 分享给微博
                                    shareWeibo(curShare, localPicUrl);
                                }
                            }
                        });
            }
        });
        sharePW.showAtLocation(mParent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        sharePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    private void shareMoment(Share share, boolean isTimelineCb, String localPicUrl) {
        WXManager.instance().sendWebPageToWX(
                isTimelineCb,
                share.getAddress(),
                TextUtils.isEmpty(share.getTitle()) ? " " : share.getTitle(),
                share.getDescribe(),
                localPicUrl);
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    private void shareWeibo(Share share, String localPicUrl) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.textObject = getTextObj(share);
        weiboMessage.imageObject = getImageObj();
        weiboMessage.mediaObject = getWebpageObj(share);
        weiboMessage.multiImageObject = getMultiImageObject(localPicUrl);
        shareHandler.shareMessage(weiboMessage, false);

    }

    /**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     */
    private TextObject getTextObj(Share share) {
        TextObject textObject = new TextObject();
        textObject.text = share.getTitle();
        return textObject;
    }

    private ImageObject getImageObj() {
        ImageObject imageObject = new ImageObject();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_share_wb);
        imageObject.setImageObject(bitmap);
        return imageObject;
    }

    private BaseMediaObject getWebpageObj(Share share) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = share.getTitle();
        mediaObject.description = getString(R.string.app_name);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_logo);
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = share.getAddress();
        mediaObject.defaultText = "Webpage 默认文案";
        return mediaObject;
    }

    private MultiImageObject getMultiImageObject(String localPicUrl) {
        MultiImageObject multiImageObject = new MultiImageObject();
        //pathList设置的是本地本件的路径,并且是当前应用可以访问的路径，现在不支持网络路径（多图分享依靠微博最新版本的支持，所以当分享到低版本的微博应用时，多图分享失效
        // 可以通过WbSdk.hasSupportMultiImage 方法判断是否支持多图分享,h5分享微博暂时不支持多图）多图分享接入程序必须有文件读写权限，否则会造成分享失败
        ArrayList<Uri> pathList = new ArrayList<>();
        pathList.add(FileProvider7.getUriForFile(this, new File(localPicUrl)));
        multiImageObject.setImageList(pathList);
        return multiImageObject;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null != shareHandler) {
            shareHandler.doResultIntent(intent, this);
        }
    }

    @Override
    public void onWbShareSuccess() {
        ToastUtils.showShort("分享成功");
    }

    @Override
    public void onWbShareCancel() {
        ToastUtils.showShort("分享取消");
    }

    @Override
    public void onWbShareFail() {
        ToastUtils.showShort("分享失败");
    }

    /**
     * 页面回退
     * YouzanBrowser.pageGoBack()返回True表示处理的是网页的回退
     */
    @Override
    public void onBackPressed() {
        if (!mWebView.pageGoBack()) {
            super.onBackPressed();
        }
    }
}
